class GalleriesController < ApplicationController
  before_filter :find_gallery,                        :only => [:show,    :edit,    :update,  :destroy, :approvals, :send_request]
  before_filter :require_login,                       :only => [:create,  :edit,    :new,     :update,  :destroy]
  before_filter :require_admin,                       :only => [:index,   :new,     :create,  :edit,    :destroy]
  before_filter :find_list_items
  before_filter :check_gallery_permissions,           :only => [:show]
  before_filter :restrict_approvals_and_dependents,   :only => [:approvals,         :send_request]
  
  def index
    if params[:filter]
      order = (params[:filter][:gallery_attribute].blank? ? '' : params[:filter][:gallery_attribute]) + (params[:filter][:gallery_attribute_order].blank? ? '' : " #{params[:filter][:gallery_attribute_order]}")
      conditions = (params[:filter][:boolean_gallery_attribute].blank? ? '': "#{params[:filter][:boolean_gallery_attribute]} = 1")
      conditions.blank? ? (params[:filter][:price_list].blank? ? (conditions << "price_list_id IS NULL") : ((params[:filter][:price_list] == "all") ? "" : (conditions << "price_list_id = #{params[:filter][:price_list]}"))) : (params[:filter][:price_list].blank? ? (conditions << " AND price_list_id IS NULL") : ((params[:filter][:price_list] == "all") ? "" : (conditions << " AND price_list_id = #{params[:filter][:price_list]}")))
      conditions.blank? ? (conditions << "gallery_template_id = #{params[:filter][:gallery_template]}" unless params[:filter][:gallery_template].blank?) : (conditions << " AND gallery_template_id = #{params[:filter][:gallery_template]}" unless params[:filter][:gallery_template].blank?)
      @galleries = Gallery.find(:all, :order => (order.blank? ? "created_at desc" : order), :conditions => conditions)
      @galleries.reject! {|gallery| !gallery.users.include?(User.find(params[:filter][:user]))} unless params[:filter][:user].blank?
      @galleries.reject! {|gallery| !gallery.pages.include?(Page.find(params[:filter][:page]))} unless params[:filter][:page].blank?
    else
      @galleries = Gallery.find(:all, :order => 'created_at desc')
    end
    (@galleries.reject! {|gallery| !current_user.authorized_to_view?(gallery)}) if logged_in?
    (@galleries.reject! {|gallery| gallery.private? or gallery.invisible?}) unless logged_in?
    @galleries = @galleries.paginate :page => params[:page], :per_page => 12
  end
  
  def show
    respond_to do |gallery|
      gallery.html  {}
      gallery.xml   {render :xml => @gallery.xml(logged_in?, current_user, login_url)}
    end
    @gallery.all_items = @gallery.all_items.paginate :page => params[:page], :per_page => 36
  end
  
  def new
    @gallery  = Gallery.new
    @photos   = Photo.find_all_by_parent_id(nil)
  end
  
  def create
    @gallery = Gallery.new(params[:gallery])
    @gallery.save!
    flash[:update] = "The gallery \"#{@gallery.name}\" has been created. Now you can add some photos to it..."
    redirect_to new_photo_url
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'Errors were detected, see below.'
    render :action => 'new'
  end
  
  def edit
  end
  
  def update
    params[:gallery][:invisible] ||= []
    params[:gallery][:for_proofing] ||= []
    params[:gallery][:user_ids] ||= []
    params[:gallery][:page_ids] ||= []
    params[:gallery][:is_approved] ||= []
    params[:gallery][:approval_items] ||= []
    if params[:commit] == "send approvals"
      @gallery.update_attributes(params[:gallery])
      @gallery.is_approved = true
      @gallery.save!
      mail = Notifier.create_new_approval(@gallery.reload)
      if Notifier.deliver(mail)
        flash[:update] = "A notification of your approvals has been sent to Dan Stewart."
      else
        flash[:error] = "There was a problem sending the notification"
      end
      @gallery.create_approved_gallery
      redirect_to gallery_approvals_url(@gallery)
    else
      @gallery.update_attributes!(params[:gallery])
      flash[:update] = 'The gallery has been updated'
      redirect_to gallery_url
    end
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'Errors were detected, see below.'
    render :action => 'edit'
  end
  
  def destroy
    params[:gallery][:destroy_all_photos] ||= "0"
    params[:gallery][:destroy_all_photos_except] ||= "0"
    params[:gallery][:destroy_all_videos] ||= "0"
    params[:gallery][:destroy_all_videos_except] ||= "0"
    ((params[:gallery][:destroy_all_photos_except] == "1") ? (@gallery.photos.each {|photo| photo.destroy unless photo.in_more_than_one_gallery?}) : (@gallery.photos.each {|photo| photo.destroy})) if params[:gallery][:destroy_all_photos] == "1"
    ((params[:gallery][:destroy_all_videos_except] == "1") ? (@gallery.videos.each {|video| video.destroy unless video.in_more_than_one_gallery?}) : (@gallery.videos.each {|video| video.destroy})) if params[:gallery][:destroy_all_videos] == "1"
    @gallery.destroy
    flash[:update] = 'The gallery has been deleted'
    redirect_to galleries_url
  end
  
  def approvals
  end
  
  def send_request
    mail = Notifier.create_new_approval(@gallery, ItemOption.find(:all))
    if Notifier.deliver(mail)
      flash[:update] = "A notification of your approvals has been sent to Dan Stewart."
      @gallery.is_approved = true
      @gallery.save!
    else
      flash[:error] = "There was a problem sending the notification"
    end
    redirect_to gallery_url(@gallery)
  end
  
protected
  def find_gallery
    @gallery = Gallery.find(params[:id], :include => [:photos, :videos])
  end
  def check_gallery_permissions
    if @gallery.private?
      if logged_in?
        unless current_user.is_admin?
          unless @gallery.users.include?(current_user)
            flash[:error] = "Sorry, you're not allowed to see that gallery."
            redirect_back_or_default('/')
          end
        end
      else
        session[:return_to] = request.request_uri
        flash[:error] = "You gotta login to see that gallery."
        redirect_to login_url
      end
    end
  end
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def require_admin
    unless current_user.is_admin?
      flash[:error] = "You must be an administrator to do that, sorry."
      redirect_back_or_default('/')
    end
  end
  def find_list_items
    @item_options = ItemOption.find(:all)
    @users = User.find(:all, :conditions => ['is_client = ?', true], :order => 'login asc')
    @thumbnails = Photo.find(:all, :conditions => ["is_thumbnail = ?", true], :order => 'created_at desc')
    @videos = Video.find(:all, :order => 'created_at desc').paginate :page => params[:page], :per_page => 24, :order => 'title asc'
    @photos = Photo.find(:all, :conditions => ['parent_id IS ?', nil], :order => 'created_at desc').paginate :page => params[:page], :per_page => 24, :order => 'created_at'
    @price_lists = PriceList.find(:all, :order => 'name asc')
    @pages = Page.find(:all, :order => 'title asc')
    @gallery_templates = GalleryTemplate.find(:all, :order => 'name asc')
  end
  def restrict_approvals_and_dependents
    unless @gallery.for_proofing?
      flash[:error] = "You can't do that because this gallery isn't a proofing gallery"
      redirect_to gallery_url(@gallery)
    end
  end
end